﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.SignalR;

namespace Zocono.Infrastructure.Common
{
    /// <summary>
    /// ServiceCollection
    /// </summary>
    public static class ServiceCollectionExt
    {
        public static IServiceProvider serviceProvider { get; set; }

        /// <summary>
        /// Configuration
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddConfiguration(this IServiceCollection services, IConfigurationRoot configuration)
        {
            return services.AddSingleton(configuration);
        }

        /// <summary>
        /// Nlog
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddNlog(this IServiceCollection services)
        {
            return services.AddSingleton<ILogUtil, NlogUtil>();
        }

        /// <summary>
        /// AddSignalR
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddSignalRClient(this IServiceCollection services)
        {
            return services.AddSingleton<SignalRClient>();
        }


        public static IServiceCollection AddOption<T>(this IServiceCollection services, string key, IConfiguration configuration) where T : class, new()
        {
            if (key.IsEmpty())
            {
                throw new ArgumentNullException(nameof(key));
            }
            //CheckNull.ArgumentIsNullException(key, nameof(key));
            return services.AddOptions().Configure<T>(option => configuration?.GetSection(key));
        }

        public static IServiceCollection AddRedisCache(this IServiceCollection services)
        {
            return services.AddSingleton<IRedisHelper, RedisHelper>();
        }


        public static IServiceCollection AddLazy(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Transient)
        {
            switch (lifetime)
            {
                case ServiceLifetime.Singleton:
                    return services.AddSingleton(typeof(Lazy<>));

                case ServiceLifetime.Scoped:
                    return services.AddScoped(typeof(Lazy<>));

                case ServiceLifetime.Transient:
                    return services.AddTransient(typeof(Lazy<>));

                default:
                    return services.AddTransient(typeof(Lazy<>));
            }
        }
    }
}
